import 'dart:io';

import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:app/src/config/app_data_config.dart';
import 'package:app/src/http/bean/clockin/clokin_subdata_type.dart';
import 'package:app/src/ui/app_ui.dart';
import 'package:app/src/http/bean/banner.dart';
import 'package:app/src/http/bean/http_data.dart';
import 'package:app/src/http/bean/user.dart';
import 'package:app/src/http/sign.dart';
import 'package:app/src/http/url.dart';
import 'package:app/src/manager/user_manager.dart';
import 'package:app/src/ui/dialog/dailog.dart';

import '../bean/clockin/attendances.dart';
import '../bean/clockin/clock_in.dart';
import '../bean/clockin/clockin_point_range.dart';

///打卡簽到
class ClokinModel {
  ///打卡签到获取最新的签到记录接口;(会获取签到班组，以及所有的班组和班次信息)
  static void getAppSignInHandlerWithGetPointRange(
      BuildContext context,
      bool isEnableLoad,
      ResponseCallbackWithT<AppHttpResult<ClokinPointRange?, String?>>
          callback) {
    var url = Url.baseurl() + Url.AppSignInHandler;
    var queryParameters = Map<String, dynamic>();
    var token = AppDataConfig.getToken();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // subData.businessdata =
    //     ClokinSubDataType.getClokinSubDataType(ClokinSubDataType.GetPointRange);
    // queryParameters['data'] = subData.jsonEncodeToJson();
    var data =
        ClokinSubDataType.getClokinSubDataType(ClokinSubDataType.GetBaseData);
    queryParameters['data'] = data.jsonEncodeToJson();
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    //获取最新打卡信息：http://192.168.1.5:8888/Android/AppSignInHandler.ashx
    // print("获取最新打卡信息：$url");
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        print('错误:\t$code\t$error');
        if (isEnableLoad) {
          AppDialog.showDialogWithError(context, code, error);
        }
      })
      ..onSuccess((result) {
        // PrintUtils.printlnLong('打卡最新记录获取成功:\n$result');
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..isAllowedRepeat = false //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<ClokinPointRange?, String?>>(AppHttpResult()
            ..Data = ClokinPointRange()
            ..t2 = "")
          ?.then((result) {
        var json = result?.Data?.WorkInfo?.jsonEncodeToJson();
        //PrintUtils.printlnLong("最新打卡记录请求结果：=======================================$json");
        callback?.call(result);
      });
  }

  ///根据班组，获取对应的班次。
  static void GetShifts(
      BuildContext context,
      bool isEnableLoad,
      MyGroupBcInfo? GroupBcInfo,
      ResponseCallbackWithT<AppHttpResult<List<MyAttendances>?, MyAttendances?>>
          callback) {
    if (StringUtils.isEmpty(GroupBcInfo?.GroupId)) {
      return;
    }
    var url = Url.baseurl() + Url.checkTimeHandler;
    var queryParameters = Map<String, dynamic>();
    var token = AppDataConfig.getToken();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // subData.businessdata =
    //     ClokinSubDataType.getClokinSubDataType(ClokinSubDataType.GetPointRange);
    // queryParameters['data'] = subData.jsonEncodeToJson();
    ClokinSubmit clokinSubmit = ClokinSubmit();
    clokinSubmit.type = ClokinSubDataType.GetGroupBcDateByGroupId;
    clokinSubmit.groupId = GroupBcInfo?.GroupId;
    var data = clokinSubmit;
    String json=data.jsonEncodeToJson();
    // PrintUtils.printlnLong(
    //     '================================================获取班次参数:\n$json');
    queryParameters['data'] = json;
    queryParameters['type'] = ClokinSubDataType.GetGroupBcDateByGroupId;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        //{"MsgCode":"100","MsgDetail":null,"Data":[{"AttendanceId":109,"WorkTypeName":"d","OnWorkTime":"2022-08-10 11:00","OffWorkTime":"2022-08-10 11:10"}]}
        // PrintUtils.printlnLong(
        //     '================================================获取班次:\n$result');
        // print("获取班次:\n$result");
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..isAllowedRepeat = false //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<List<MyAttendances>?, MyAttendances?>>(
              AppHttpResult()
                ..Data = <MyAttendances>[]
                ..t2 = MyAttendances())
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }

  ///判断是否能够正常签退；100能够正常签退；102需要用户二次确认才能签退。
  static void isCheckTimeHandler(
      BuildContext context,
      bool isEnableLoad,
      ClokinSubmit clokinSubmit,
      ResponseCallbackWithT<AppHttpResult<String?, String?>> callback) {
    var url = Url.baseurl() + Url.checkTimeHandler;
    var queryParameters = Map<String, dynamic>();
    var token = AppDataConfig.getToken();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // subData.businessdata =
    //     ClokinSubDataType.getClokinSubDataType(ClokinSubDataType.GetPointRange);
    // queryParameters['data'] = subData.jsonEncodeToJson();
    var data = clokinSubmit;
    queryParameters['data'] = data.jsonEncodeToJson();
    queryParameters['type'] = ClokinSubDataType
        .GetSignOut; //data.type; //fixme ClokinSubDataType.GetSignOut
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    // var starData = DateTime.now();
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      ..onStart(() {
        // print('开始  ${Url.checkTimeHandler}');
      })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        //{"MsgCode":"100","MsgDetail":"签到成功，请联系班长进行确认！","Data":true}
        // var starData2 = DateTime.now();
        // var d = starData2.difference(starData);
        // PrintUtils.printlnLong(
        //     '================================================判断是否能够签退:\n$result耗时：${d.inSeconds}秒');
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..isAllowedRepeat = false //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String?, String?>>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        callback?.call(result);
      });
  }

  ///签到打卡。(上班打卡)
  static void CheckTimeIn(
      BuildContext context,
      bool isEnableLoad,
      ClokinSubmit clokinSubmit,
      ResponseCallbackWithT<AppHttpResult<String?, String?>> callback) {
    var url = Url.baseurl() + Url.checkTimeHandler;
    var queryParameters = Map<String, dynamic>();
    var token = AppDataConfig.getToken();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // subData.businessdata =
    //     ClokinSubDataType.getClokinSubDataType(ClokinSubDataType.GetPointRange);
    // queryParameters['data'] = subData.jsonEncodeToJson();
    var data = clokinSubmit;
    queryParameters['data'] = data.jsonEncodeToJson();
    queryParameters['type'] = ClokinSubDataType.CheckTimeIn;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    // var starData = DateTime.now();
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      ..onStart(() {
        // print('开始签到：\t${Url.checkTimeHandler}');
      })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        //{"MsgCode":"100","MsgDetail":"签到成功，请联系班长进行确认！","Data":true}
        var starData2 = DateTime.now();
        // var d = starData2.difference(starData);
        // PrintUtils.printlnLong(
        //     '================================================签到打卡:\n$result 耗时：${d.inSeconds}秒');
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..isAllowedRepeat = false //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<String?, String?>>(AppHttpResult()
            ..Data = ""
            ..t2 = "")
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }

  ///签退打卡。（下班打卡）
  static void CheckTimeOut(
      BuildContext context,
      bool isEnableLoad,
      ClokinSubmit clokinSubmit,
      ResponseCallbackWithT<AppHttpResult<WageField?, String?>> callback) {
    var url = Url.baseurl() + Url.checkTimeHandler;
    var queryParameters = Map<String, dynamic>();
    var token = AppDataConfig.getToken();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // subData.businessdata =
    //     ClokinSubDataType.getClokinSubDataType(ClokinSubDataType.GetPointRange);
    // queryParameters['data'] = subData.jsonEncodeToJson();
    var data = clokinSubmit;
    queryParameters['data'] = data.jsonEncodeToJson();
    queryParameters['type'] = ClokinSubDataType.CheckTimeOut;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    // var starData = DateTime.now();
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      ..onStart(() {
        // print('开始签退：\t${Url.checkTimeHandler}');
      })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        //{"MsgCode":"100","MsgDetail":"签到成功，请联系班长进行确认！","Data":true}
        // var starData2 = DateTime.now();
        // var d = starData2.difference(starData);
        // PrintUtils.printlnLong(
        //     '================================================签退打卡:\n$result耗时：${d.inSeconds}秒');
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..isAllowedRepeat = false //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<WageField?, String?>>(AppHttpResult()
            ..Data = WageField()
            ..t2 = "")
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }

  ///工资结算
  static WageField? wageField = null;

  static void GetgetWageSettlement(BuildContext context, bool isEnableLoad,
      ResponseCallbackWithT<AppHttpResult<WageSettlement?, String?>> callback) {
    if (wageField == null) {
      return;
    }
    var url = Url.baseurl() + Url.checkTimeHandler;
    var queryParameters = Map<String, dynamic>();
    var token = AppDataConfig.getToken();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // subData.businessdata =
    //     ClokinSubDataType.getClokinSubDataType(ClokinSubDataType.GetPointRange);
    // queryParameters['data'] = subData.jsonEncodeToJson();
    var data = wageField;
    String? dataJson = data?.jsonEncodeToJson();
    // PrintUtils.printlnLong(
    //     '================================================工资结算参数:\n$dataJson');
    queryParameters['data'] = dataJson;
    queryParameters['type'] = ClokinSubDataType.GetWageSettlement;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    // print("获取工资结算$url");
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        //{"MsgCode":"100","MsgDetail":"签到成功，请联系班长进行确认！","Data":true}
        // PrintUtils.printlnLong(
        //     '================================================工资结算:\n$result');
        //{"MsgCode":"101","MsgDetail":"没有找到您所要查询的日结数据;","Data":null}
        // print("工资结算：$result");
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..isAllowedRepeat = false //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<WageSettlement?, String?>>(AppHttpResult()
            ..Data = WageSettlement()
            ..t2 = "")
          ?.then((result) {
        //print("请求结果：=======================================");
        callback?.call(result);
      });
  }

  ///打卡签到记录
  static void GetGroupChekTimeList(
      BuildContext context,
      bool isEnableLoad,
      ClokinHistoricalRecord clokinHistoricalRecord,
      ResponseCallbackWithT<AppHttpResult<List<ClockinInfo>?, ClockinInfo?>>
          callback) {
    var url = Url.baseurl() + Url.checkTimeHandler;
    var queryParameters = Map<String, dynamic>();
    var token = AppDataConfig.getToken();
    // var subData = SubData();
    // subData.commondata = CommonData();
    // subData.businessdata =
    //     ClokinSubDataType.getClokinSubDataType(ClokinSubDataType.GetPointRange);
    // queryParameters['data'] = subData.jsonEncodeToJson();
    var data = clokinHistoricalRecord;
    queryParameters['data'] = data.jsonEncodeToJson();
    queryParameters['type'] = data.type;
    var sign = getSign(queryParameters);
    queryParameters['sign'] = sign;
    //print('签名：$sign');
    KOhttp(url)
      ..isEnableLoad(isEnableLoad, context)
      // ..onStart(() {
      //   print('开始');
      // })
      ..onError((code, error) {
        // print('错误:\t$code\t$error');
        AppDialog.showDialogWithError(context, code, error);
      })
      ..onSuccess((result) {
        // PrintUtils.printlnLong('================================================打卡记录:\n$result');
      })
      // ..onFinish(() {
      //   print('结束');
      // })
      ..isCache(false)
      ..addHeader('token', token)
      ..addFormDatas(queryParameters)
      ..isAllowedRepeat = false //是否允许重复请求
      ..isUpdateCallback = true //实时更新回调函数
      ..contentType = ContentType.form
      ..isEnableLog = AppDataConfig.isEnableLog
      ..postASync<AppHttpResult<List<ClockinInfo>?, ClockinInfo?>>(
              AppHttpResult()
                ..Data = <ClockinInfo>[]
                ..t2 = ClockinInfo())
          ?.then((result) {
        // print(
        //     "打卡签到记录请求结果：=======================================${result?.Data?.length}");
        callback?.call(result);
      });
  }
}
